var map;
var directionDisplay;
var directionsService;
var stepDisplay;
var popshouse;

function initialize() {

  directionsService = new google.maps.DirectionsService();

  popshouse = new google.maps.LatLng(50.83940, 2.73563);
  var myOptions = {
    zoom: 16,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: popshouse
  }

  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    
  var rendererOptions = {
    map: map
  }
  directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions)

  var image = new google.maps.MarkerImage('../images/layout/icons/popshouse.png',
	      // This marker is 20 pixels wide by 32 pixels tall.
	      new google.maps.Size(30, 30),
	      // The origin for this image is 0,0.
	      new google.maps.Point(0,0),
	      // The anchor for this image is the base of the flagpole at 0,32.
	      new google.maps.Point(15, 15));
  var homeMarker = new google.maps.Marker({
      position: popshouse,
      map: map,
      icon: image
  });
  
  stepDisplay = new google.maps.InfoWindow();
  google.maps.event.addListener(homeMarker, 'click', function() {
	    stepDisplay.setContent("Popshouse Bed &amp; Breakfast");
	    stepDisplay.open(map, homeMarker);
	    toggleBounce(homeMarker,true);
	  });

  $('a[rel="calc"]').click(calcRoute);
}

function calcRoute() {
	$(".steps").slideUp();
  var start = $('input[name="start"]').val();
  var request = {
      origin: start,
      destination: popshouse,
      travelMode: google.maps.DirectionsTravelMode.DRIVING
  };
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      var warnings = $("#warnings_panel");
      warnings.html("" + response.routes[0].warnings + "");
      directionsDisplay.setDirections(response);
      showSteps(response);
    }
  });
}

function showSteps(directionResult) {
  var myRoute = directionResult.routes[0].legs[0];
  var steps = "";
  for (var i = 0; i < myRoute.steps.length; i++) {   
	  steps += "<li>" + myRoute.steps[i].instructions + "</li>";
  }
  $("#step_list").html(steps);
  $(".steps").slideDown();
}

function toggleBounce(marker,start) {
	if(start){
		marker.setAnimation(google.maps.Animation.BOUNCE);
		setTimeout(function() { toggleBounce(marker,false); },3500);
	}else{
		 marker.setAnimation(null);
	}
}
	

function attachInstructionText(marker, text) {
  google.maps.event.addListener(marker, 'click', function() {
    stepDisplay.setContent(text);
    stepDisplay.open(map, marker);
  });
}

$(document).ready(function() {
    initialize();
});